package com.lichuandi.crawler;

import com.google.gson.JsonParser;
import org.apache.commons.net.io.Util;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/crawler")
public class SichuanAirCrawlerController {
    @GetMapping("/sichuanair2")
    public String getPageContent() {
        try {
            // 登录的主页面
            final String url = "https://me.sichuanair.com/login.shtml"; // 要爬取的网页URL
            // 提交表单登录的页面
            final String url2 = "https://me.sichuanair.com/api/v1/security/loginSC"; // 要爬取的网页URL
            // 验证码的页面
            String logs = "https://me.sichuanair.com/verifyScCode?t_" + new Date().getTime();

            // 登录的参数
            HashMap<String, String> data = new HashMap<>();
            data.put("username", "o18750");
            data.put("userPassword", "NUvjWmbmzFZIS1hOd0Uo0rXjJcF/W+94PTT1DBLyAV2dIALLMMktJjjY6y4AQD+QXbkxNgASvSjEMC2ldO+14g==");
            data.put("vCode", "ABAB");
            // 先登录一次
            Connection.Response loginFirst = Jsoup.connect(url2)
                    .ignoreContentType(true)
                    .followRedirects(false)
                    .postDataCharset("utf-8")
                    .header("Upgrade-Insecure", "1")
                    .header("Accept", "application/json")
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .header("X-Requested-With", "XMLHttpRequest")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36")
                    .data(data).method(Connection.Method.POST).execute();
            Map<String, String> cookies = loginFirst.cookies();
            System.out.println(cookies);
            // 获取sessionID
            String jsessionid = loginFirst.cookie("JSESSIONID");

            int i = loginFirst.statusCode();
            System.out.println(i);

            String code = JsonParser.parseString(loginFirst.body()).getAsJsonObject().get("code").getAsString();
            /*if (code.equals("907")){
                // 登录失败刷新验证码
                URL urlCode = new URL(logs);
                getStream(urlCode);
                String vCode = chaojiyingCode();
                data.put("vCode", vCode);
            }*/

            // 或者使用请求的方式Get，验证码

            Connection.Response execute = Jsoup.connect(logs).header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36")
                    .ignoreContentType(true).followRedirects(false).method(Connection.Method.GET).cookies(loginFirst.cookies()).execute();
            System.out.println(execute.cookies());
            Map<String, String> cookies2 = execute.cookies();
            byte[] bytes = execute.bodyAsBytes();
            //URLEncoder.encode();
            String s = ChaoJiYing.PostPic("amfreak", "qwe12345", "914695", "3004", "0", bytes);
            System.out.println(s);
            String pic_str = JsonParser.parseString(s).getAsJsonObject().get("pic_str").getAsString();
            System.out.println(pic_str);
            data.put("vCode", pic_str);


            // 再次登录
            Connection.Response response = Jsoup.connect(url2).header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36")
                    .ignoreContentType(true).followRedirects(false).method(Connection.Method.POST).data(data).cookies(loginFirst.cookies()).execute();
            Map<String, String> cookies1 = response.cookies();
            System.out.println(cookies1);

            String body = response.body();


            //return loginFirst.body();
            // 爬取的内容
            // sichuanAirWebContent();
            return body;
        } catch (Exception e) {
            return "Error: " + e.getMessage();
        }
    }

    private void sichuanAirWebContent() throws IOException {
        String sessionId = null;
        String url = "https://me.sichuanair.com/api/v1/plugins/LM_FLIGHT_SEARCH_LIST";
        Document document = Jsoup.connect(url).cookie("JSESSIONID", sessionId).timeout(10000).get();


    }

    private String chaojiyingCode() {
        // 获取超级鹰的验证码
        String postPic = ChaoJiYing.PostPic("amfreak", "qwe12345", "914695", "3004", "0", "F:\\vcode\\myVCode.jpg");
        String pic_str2 = JsonParser.parseString(postPic).getAsJsonObject().get("pic_str").getAsString();
        System.out.println(pic_str2);
       return pic_str2;
    }

    public void getStream(URL url1) throws IOException {
        InputStream inputStream = url1.openStream();
        FileOutputStream outputStream = new FileOutputStream("F:\\vcode\\myVCode.jpg");
        byte[] bytes = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes,0, bytesRead);
        }
        outputStream.close();
        inputStream.close();
    }

}
